package ch01.observer;

import java.util.Observable;
import java.util.Observer;

/**
 * Created by zc on 2016/10/25.
 */
public class SimpleTest {

    public static void main(String[] args){
        SimpleObservable doc = new SimpleObservable ("Hello Java");
        SimpleObserver view = new SimpleObserver (doc);

        ObserverQueue queue = new ObserverQueue();
        Thread threadPacker = new Thread(queue);
        view.attachObservable(queue);
        threadPacker.start();
        queue.attachObservable(doc);
        doc.changeInstate("Hello Scala");

    }
}

class SimpleObservable extends Observable {
    private String inState;

    public SimpleObservable(String inState) {
        this.inState = inState;
    }

    public void changeInstate(String newState){
        if(!newState.equals(inState)){
            this.inState = newState;
            setChanged();
        }
        notifyObservers();
    }

    public String getState() {
        return inState;
    }
}

class SimpleObserver implements Observer {

    public SimpleObserver(SimpleObservable so) {
        so.addObserver(this);
    }

    public void attachObservable(Observable watched){
        watched.addObserver(this);
    }

    @Override
    public void update(Observable o, Object arg) {
        System.out.println("Data has changed to" + ((SimpleObservable) o).getState());
    }
}
